import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/cookie'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// request拦截器
service.interceptors.request.use(
  config => {
    // console.log(getToken()+":"+store.getters.token)
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 上传文件修改默认请求头
service.defaults.transformRequest = [function (data, config) {
  if (!config['Content-Type']) return JSON.stringify(data)
  switch (config['Content-Type'].toLowerCase()) {
    case 'application/json;charset=utf-8': {
      return JSON.stringify(data)
    }
    case 'multipart/form-data;charset=utf-8': {
      return data
    }
    default: {
      return JSON.stringify(data)
    }
  }
}]

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 0) {
      Message({
        message: res.errMsg,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      console.log(response)
      return response.data.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
